package com.cg.util;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Base64;
import java.util.Map;
import java.util.TreeMap;

public class NftHashUtils {
    public static String canonicalizeJsonText(String json, ObjectMapper mapper) {
        try {
            Map<String, Object> map = mapper.readValue(json, new TypeReference<Map<String, Object>>(){});
            return canonicalize(map, mapper);
        } catch (Exception e) {
            return json;
        }
    }

    public static String canonicalize(Map<String, Object> data, ObjectMapper mapper) {
        try {
            TreeMap<String, Object> sorted = new TreeMap<>(data);
            return mapper.writeValueAsString(sorted);
        } catch (Exception e) {
            return data.toString();
        }
    }

    public static String sha256Hex(String text) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            byte[] out = md.digest(text.getBytes(StandardCharsets.UTF_8));
            StringBuilder sb = new StringBuilder();
            for (byte b : out) sb.append(String.format("%02x", b));
            return sb.toString();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static String toNftId(String hashHex) {
        return Base64.getUrlEncoder().withoutPadding().encodeToString(hashHex.getBytes(StandardCharsets.UTF_8));
    }
}


